<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <canvas
      id="canvas"
      width="300"
      height="300"
      style="outline: 1px solid red"
    ></canvas>
    <button onclick="clearR()">clear</button>

    <script>
      function clearR() {
        console.log(123);
        context.clearRect(0, 0, 300, 300);
      }

      const canvas = document.querySelector("#canvas");
      const context = canvas.getContext("2d");
      context.lineWidth = 2;

      canvas.onmousedown = function (event) {
        context.beginPath();
        context.moveTo(event.offsetX, event.offsetY);
        // 节流
        let flag = true;
        setInterval(() => {
          flag = true;
        }, 30);
        canvas.onmousemove = function (ev) {
          if (flag) {
            context.lineTo(ev.offsetX, ev.offsetY);
            context.stroke();
            flag = false;
          }
        };
      };
      document.body.onmouseup = function () {
        canvas.onmousemove = null;
      };
    </script>
  </body>
</html>
